<template>
    <div>
        <el-form ref="form"   size="small">
            <!-- <el-form-item >
                <el-col :span="20">
                    <el-button  size="small" type="primary"  @click="importModel">模板导入</el-button>
                    <el-input class="elInput" v-model="num" placeholder="" size="small">
                        <template slot="prepend">生成数量(张)</template>
                    </el-input>
                </el-col>
                <el-col :span="4" class="tr">
                    <el-button  size="small" type="primary"  @click="generate">生成</el-button>
                </el-col>
            </el-form-item> -->
            <el-form-item>
                <el-col :span="20">
                    <el-input class="elInput elInp" v-model="searchVal" placeholder="请输入二维码编号或通道编号" size="small" ></el-input>
                    <el-button  size="small" type="primary" @click="searchData">搜索</el-button>
                </el-col>
                <el-col :span="4" class="tr">
                    <el-button  size="small" type="primary"  @click="generate">生成二维码</el-button>
                    <el-button  size="small" type="primary"  @click="downloadZip">下载</el-button>
                </el-col>
            </el-form-item>
        </el-form>
        <div class="boxList" v-loading="listLoading">
            <el-table :data="tableData.records" border  empty-text="暂无数据"  @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55"></el-table-column>
                <el-table-column type="index"  label="序号"  width="70"  align="center" :index="indexMethod"></el-table-column>
                <el-table-column prop="id" label="二维码编号" align="center" min-width="120"></el-table-column>
                <el-table-column prop="parkName" label="车场名称"  align="center" min-width="120"></el-table-column>
                <el-table-column prop="laneId" label="通道编号"  align="center" min-width="120"></el-table-column>
                <el-table-column prop="bindTime" label="绑定时间"  align="center" min-width="120">
                    <template slot-scope="scope">
                        <span v-if="scope.row.status==1">{{scope.row.bindTime}}</span>
                        <span v-else>--</span>
                    </template>
                </el-table-column>
                <el-table-column prop="bindUrl" label="绑定链接"  align="center" min-width="120"></el-table-column>
                <el-table-column label="状态"  align="center" min-width="120">
                    <template slot-scope="scope">
                        <span v-if="scope.row.isStop!=1&&scope.row.status==0">未绑定</span>
                        <span v-if="scope.row.isStop!=1&&scope.row.status==1">已绑定</span>
                        <span v-if="scope.row.isStop==1">停用</span>
                    </template>
                </el-table-column>
                <el-table-column label="操作"  align="center" min-width="180">
                    <template slot-scope="scope">
                        <el-button size="mini" type="danger" @click="stopUse(scope.row)" v-if="scope.row.isStop==0">停用</el-button>
                        <el-button size="mini" type="danger" @click="startUse(scope.row)" v-if="scope.row.isStop==1">启用</el-button>
                        <el-button size="mini" type="primary" @click="bindQrcode(scope.row)" v-if="scope.row.status==0">绑定</el-button>
                        <el-button size="mini" type="primary" @click="unbundling(scope.row)" v-if="scope.row.status==1">解绑</el-button>
                        <el-button size="mini" type="primary" @click="lookQrcode(scope.row)">查看二维码</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="fenye">
                <span class="demonstration"></span>
                <el-pagination background 
                    @size-change="handleSizeChange" 
                    @current-change="handleCurrentChange" 
                    :current-page="params.pageNo"
                    :page-sizes="[10, 20, 30, 40,50]" 
                    :page-size="10" 
                    layout="total, sizes, prev, pager, next, jumper" 
                    :total="tableData.total">
                </el-pagination>
            </div>
        </div>
        <!-- 生成二维码 -->
        <el-dialog
            title="生成二维码"
            :visible.sync="dialogVisible"
            :close-on-click-modal="false"
            width="60%" v-loading="dialogLoading">
            <el-form ref="form" :model="formAdd" size="mini">
                <el-form-item label="上传模板：" label-width="120px">
                    <el-upload
                        class="avatar-uploader"
                        action="/"
                        :show-file-list="false"
                        :auto-upload="false"
                        :on-change="imgSaveToUrl"
                        :accept="'image/*'">
                        <el-button size="small" type="primary">点击上传</el-button>
                    </el-upload>
                </el-form-item>
                <el-form-item label="上传Logo：" label-width="120px">
                    <el-upload
                        class="avatar-uploader"
                        action="/"
                        :show-file-list="false"
                        :auto-upload="false"
                        :on-change="changeFile"
                        :accept="'image/*'">
                        <img v-if="logoSrc" :src="logoSrc" class="avatar">
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                </el-form-item>
                <el-form-item label="生成数量(张)：" label-width="120px">
                    <el-input class="elInput" v-model="formAdd.num" placeholder="" size="small"></el-input>
                </el-form-item>
            </el-form>
            <div class="vueDragResize" v-if="imgSrc!=''">
                <img id="uploadImg" class="uploadImg" :src="imgSrc" alt="">
                <VueDragResize :w="147" :h="147" v-on:resizing="resize" v-on:dragging="resize" :minw="50" :minh="50" :aspectRatio="true">
                　　<!-- 图片缩放 　将这个div的宽高动态设置==VueDrangResize的宽高，这样可实时完成缩放 -->
                　　<div class="box" :style="{width: + vw+ 'px',height:+vh+'px'}">
                　　<!-- 我这写的是本地的图片，图片可以动态获取 -->
                　　　　<!-- <img src="../../assets/images/codePic.png"> -->
                　　</div>
                </VueDragResize>
            </div>
            
            <span slot="footer" class="dialog-footer"> 
                <el-button type="primary" @click="confirmBtn"  size="mini">确 定</el-button>
                <el-button type="default" @click="cancelBtn"  size="mini">取消</el-button>
            </span>
        </el-dialog>
        <!-- 绑定 -->
        <el-dialog
            class="bindDialog"
            title="绑定"
            :visible.sync="bindDialogVisible"
            width="60%">
            <el-form ref="form" :model="formAdd" size="mini" style="width:100%">
                <!-- <h4 class="dialogTit">绑定车场通道</h4>
                <el-form-item>
                    <el-input class="elInputForm" v-model="formBind.laneId" placeholder="输入通道编号" size="small" @blur="visitQuery">
                        <template slot="prepend">通道编号</template>
                    </el-input>
                </el-form-item>
                <el-form-item>
                    <el-input class="elInputForm" v-model="parkName" placeholder="" size="small" disabled>
                        <template slot="prepend">车场名称</template>
                    </el-input>
                </el-form-item>
                <el-form-item>
                    <el-input class="elInputForm" v-model="laneName" placeholder="" size="small" disabled>
                        <template slot="prepend">通道名称</template>
                    </el-input>
                </el-form-item> -->
                <h4 class="dialogTit">绑定链接</h4>
                <el-form-item>
                    <el-input class="elInputForm" v-model="formBind.bindUrl" placeholder="输入网络地址" size="small">
                        <template slot="prepend">绑定链接</template>
                    </el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer"> 
                <el-button type="primary" @click="confirmBind"  size="mini">确 定</el-button>
                <el-button type="default" @click="cancelBind"  size="mini">取消</el-button>
            </span>
        </el-dialog>
        <el-dialog
            class="qrCodeDialog"
            title="绑定"
            center
            :visible.sync="qrCodeDialog"
            > <!-- width="350px" -->
            <img :src="qrCodeSrc" alt="" srcset="" style="max-width: 100%;">
        </el-dialog>
    </div>
</template>
<script>
export default {
    data() {
        return {
            listLoading:false,
            searchVal:'',
            params:{
                queryStr:'',
                pageNo:1,
                pageSize:10,
            },
            tableData:{
                records:[],
                total:0
            },
            selectNodes:[],
            dialogVisible:false,
            formAdd:{
                num:1,
                file:'',
                logo:''
            },
            picRateW:1,
            picRateH:1,
            vw: 0,
            vh: 0,
            top: 0,
            left:0,
            imgSrc:"",//require("@/assets/images/loginBg.png")
            logoSrc:'',
            bindDialogVisible:false,
            formBind:{
                id:'',
                laneId:'',
                bindUrl:'',
            },
            parkName:"",
            laneName:"",
            dialogLoading:false,
            qrCodeDialog:false,
            qrCodeSrc:''
        }
    },
    created() {
        this.vw = 147 // + "px";
        this.vh = 147 //+ "px";
        this.init()
    },
    methods: {
        resize(newRect) {
            this.vw = newRect.width;
            this.vh = newRect.height;
            this.top = newRect.top;
            this.left = newRect.left;
            console.log(this.vw,this.vh,this.top,this.left)
        },
        imgSaveToUrl(file) {
            //debugger
            const isJPEG = file.raw.type === 'image/jpeg';
            const isJPG = file.raw.type === 'image/jpg';
            const isPNG = file.raw.type === 'image/png';
            const isLt2M = file.raw.size / 1024 / 1024 < 10;

            if (!isJPG&&!isJPEG&&!isPNG) {
                this.$message.error('上传模板只能是 JPG/PNG/JPEG 格式!');
                return isJPG
            }
            if (!isLt2M) {
                this.$message.error('上传模板大小不能超过 10MB!');
                return isLt2M
                
            }
            this.formAdd.file = file.raw
            this.imgSrc = URL.createObjectURL(file.raw);
            this.$nextTick(() => {                
                this.getPicRate();
            })
            return isJPG && isLt2M;
        },
        changeFile(file){
            const isJPEG = file.raw.type === 'image/jpeg';
            const isJPG = file.raw.type === 'image/jpg';
            const isPNG = file.raw.type === 'image/png';
            const isLt2M = file.raw.size / 1024 / 1024 < 10;

            if (!isJPG&&!isJPEG&&!isPNG) {
                this.$message.error('上传Logo只能是 JPG/PNG/JPEG 格式!');
                return isJPG
            }
            if (!isLt2M) {
                this.$message.error('上传Logo大小不能超过 10MB!');
                return isLt2M
                
            }
            this.formAdd.logo = file.raw
            this.logoSrc = URL.createObjectURL(file.raw);
            return isJPG && isLt2M;
        },
        //获取图片压缩比
        getPicRate(){
            let that = this;
            let uploadImg = document.getElementById("uploadImg")
            uploadImg.onload = function() {
                that.picRateW = uploadImg.width/uploadImg.naturalWidth
                that.picRateH = uploadImg.height/uploadImg.naturalHeight
                console.log("宽：" + that.picRateW + " 高：" + that.picRateH);
            }
        },
        //序号转换
        indexMethod(index) {
            return (index + 1) + ((this.params.pageNo - 1) * this.params.pageSize);
        },
        //table上的全选
        handleSelectionChange(val) {
            this.selectNodes=[]
            let obj = {}
            val.map((item)=>{    
                this.selectNodes.push(item.id)
            })
            this.selectNodes = [...new Set(this.selectNodes)]
        },
        //分页项切换
        handleSizeChange(val) {
            this.params.pageSize = val;
            this.searchData();
        },
        //分页页码切换
        handleCurrentChange(val) {
            this.params.pageNo = val;
            this.searchData();
        },
        searchData(){
            this.params.queryStr = this.searchVal
            this.init()
        },
        init(){
            this.$api.home.getQrcodeList(this.params).then(res=>{
                //debugger
                if(res.data.code == 200){
                    //this.$message.success(res.data.message)
                    this.tableData = res.data.result
                }else{
                    this.$message.error(res.data.message)
                }
            }).catch(error=>{
                this.$message.error(error)
            })
        },
        // 模板导入
        importModel(){

        },
        // 生成
        generate(){
            this.dialogVisible = true
        },
        // 下载
        downloadZip(){
            let params = {
                ids:this.selectNodes.join(',')
            }
            let formData = new FormData()
                formData.append('ids',params.ids)
            this.$api.home.downloadQrcode(formData).then(res=>{
                //debugger
                if(res.data.code == 200){
                    window.location.href = res.data.result
                }else{
                    this.$message.error(res.data.message)
                }
            }).catch(error=>{
                this.$message.error(error)
            })
        },
        // 绑定
        bindQrcode(row){
            this.formBind.id = row.id
            this.bindDialogVisible = true
        },
        // 绑定前查询
        visitQuery(){
            if(this.formBind.laneId!==""){
                let params = {
                    laneId:this.formBind.laneId
                }
                this.$api.home.visitQuery(params).then(res=>{
                    //debugger
                    if(res.data.code == 200){
                        let result = res.data.result
                        this.parkName = result.zybParkInfo.name
                        this.laneName = result.vehicleLane.name
                    }else{
                        this.$message.error(res.data.message)
                    }
                }).catch(error=>{
                    this.$message.error(error)
                })
            }
            
        },
        // 提交绑定
        confirmBind(){
            if(this.formBind.laneId===""&&this.formBind.bindUrl===""){
                this.$message.error("请先绑定通道编号或链接")
                return
            }
            let formData = new FormData()
                formData.append('id',this.formBind.id)
                formData.append('laneId',this.formBind.laneId)
                formData.append('bindUrl',this.formBind.bindUrl)
            this.$api.home.bindingQrcode(formData).then(res=>{
                //debugger
                if(res.data.code == 200){
                    this.cancelBind()
                    this.$message.success(res.data.message)
                    this.init()
                }else{
                    this.$message.error(res.data.message)
                }
            }).catch(error=>{
                this.$message.error(error)
            })
        },
        // 取消绑定
        cancelBind(){
            this.formBind.laneId = ""
            this.formBind.bindUrl = ""
            this.bindDialogVisible = false
        },
        // 停用
        stopUse(row){
            this.$confirm('确定要停用？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
            }).then(() => {
                let formData = new FormData();
                    formData.append('id',row.id)
                this.$api.home.stopQrcode(formData).then(res=>{
                    if(res.data.code == 200){
                        this.$message.success(res.data.message)
                        this.init()
                    }else{
                        this.$message.error(res.data.message)
                    }
                }).catch((res) => {
                    this.$message({
                        message: res.message,
                        type: 'error'
                    })
                });
            }).catch((res) => {
                this.$message({
                    type: "info",
                    message:'已取消'
                });
            });
        },
        // 启用
        startUse(row){
            let formData = new FormData();
                formData.append('id',row.id)
            this.$api.home.startUse(formData).then(res=>{
                if(res.data.code == 200){
                    this.$message.success(res.data.message)
                    this.init()
                }else{
                    this.$message.error(res.data.message)
                }
            }).catch((res) => {
                this.$message({
                    message: res.message,
                    type: 'error'
                })
            });
        },
        // 解绑
        unbundling(row){
            this.$confirm('确定要解绑？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
            }).then(() => {
                let formData = new FormData();
                    formData.append('id',row.id)
                this.$api.home.unbundling(formData).then(res=>{
                    if(res.data.code == 200){
                        this.$message.success(res.data.message)
                        this.init()
                    }else{
                        this.$message.error(res.data.message)
                    }
                }).catch((res) => {
                    this.$message({
                        message: res.message,
                        type: 'error'
                    })
                });
            }).catch((res) => {
                this.$message({
                    type: "info",
                    message:'已取消'
                });
            });
        },
        
        // 确定
        confirmBtn(){
            if(this.formAdd.num == ""){
                this.$message.error('请输入生成数量')
                return
            }else if(this.formAdd.file===""){
                this.$message.error('请先上传模板')
                return
            }
            this.dialogLoading = true
            console.log(this.picRateW,'this.picRateW')
            console.log(this.picRateH,'this.picRateH')
            let vw=0,vh=0,x=0,y=0;
            if(this.picRateW!=0&&this.picRateH!=0){
                vw = parseInt(this.vw/this.picRateW) 
                vh = parseInt(this.vh/this.picRateH)
                x  = parseInt(this.left/this.picRateW)
                y  = parseInt(this.top/this.picRateH)
            }
            /* console.log(vw,vh,x,y)
            debugger */
            let formData = new FormData()
                formData.append('createNum',this.formAdd.num)
                formData.append('file',this.formAdd.file)
                formData.append('logo',this.formAdd.logo)
                formData.append('w',vw)
                formData.append('h',vh)
                formData.append('x',x)
                formData.append('y',y)
            this.$api.home.addQrcode(formData).then(res=>{
                //debugger
                if(res.data.code == 200){
                    this.dialogLoading = false
                    this.$message.success(res.data.message)
                    this.cancelBtn()
                    this.init()
                }else{
                    this.$message.error(res.data.message)
                }
            }).catch(error=>{
                this.$message.error(error)
            })
        },
        // 取消
        cancelBtn(){
            this.dialogVisible = false
            this.imgSrc = ""
            this.logoSrc = ""
            this.formAdd.file = ""
            this.formAdd.logo = ""
        },
        lookQrcode(row){
            this.getQrCode(row.id)
        },
        // 获取单个二维码
        getQrCode(id){
            let param = {
                id:id
            }
            this.$api.home.getQrCode(param).then(res=>{
                if(res.data.code == 200){
                    //this.qrCodeSrc = 'data:image/png;base64,' + res.data.result
                    this.qrCodeSrc = res.data.result
                    this.qrCodeDialog = true
                }else{
                    this.$message.error(res.data.message)
                }
            }).catch(error=>{
                this.$message.error(error)
            })
        }
    },
}
</script>
<style lang="less" scoped>
    .elInput{
        width: auto;
        &.elInp{
            min-width: 500px;
        }
    }
    .tr{
        text-align: right;
    }
    .vueDragResize{
        position: relative;
        display: inline-block;
        width: 100%;
        height:500px;
        text-align: left;
    }
    .box{
        height: 147px;
        background: url('../../assets/images/codePic.png') center no-repeat;
        background-size: 100% 100%;
    }
    .uploadImg{
        position: relative;
        max-width: 100%;
    }
    .dialogTit{
        margin:20px 0;
        text-align: center;
    }
    .bindDialog .el-form-item{
        width: 100%;
        text-align: center;
        .elInputForm{
            width: 65%;
        }
    }
    .avatar-uploader {
        display: inline-block;
        max-width: 300px;
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }
    .avatar-uploader .el-upload:hover {
        border-color: #409EFF;
    }
    .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        line-height: 178px;
        text-align: center;
    }
    .avatar {
        display: block;
        max-width: 100%;
    }
</style>